package com.wgzx.modbus.constant;

import lombok.Getter;

@Getter
public enum FunctionCode {

    READ_COILS(0x01),
    READ_DISCRETE_INPUTS(0x02),
    READ_HOLDING_REGISTERS(0x03),
    READ_INPUT_REGISTERS(0x04),
    WRITE_SINGLE_COIL(0x05),
    WRITE_SINGLE_REGISTER(0x06),
    WRITE_MULTIPLE_COILS(0x0F),
    WRITE_MULTIPLE_REGISTERS(0x10),

    READ_COILS_ERROR(0x01 + 0x80),
    READ_DISCRETE_INPUTS_ERROR(0x02+ 0x80),
    READ_HOLDING_REGISTERS_ERROR(0x03+ 0x80),
    READ_INPUT_REGISTERS_ERROR(0x04+ 0x80),
    WRITE_SINGLE_COIL_ERROR(0x05+ 0x80),
    WRITE_SINGLE_REGISTER_ERROR(0x06+ 0x80),
    WRITE_MULTIPLE_COILS_ERROR(0x0F+ 0x80),
    WRITE_MULTIPLE_REGISTERS_ERROR(0x10+ 0x80);

    private static FunctionCode[] VALUES;
    private static int MAX_LENGTH = (0x10+ 0x80 + 1);

    private short code;

    FunctionCode(int i) {
        this.code = (short) i;
    }

    static {
        VALUES = new FunctionCode[MAX_LENGTH];
        for (FunctionCode c : values()) {
            VALUES[c.code] = c;
        }
    }

    public static FunctionCode valueOf(int code) {
        if (code > 0 && code < VALUES.length) {
            return VALUES[code];
        } else {
            throw new IllegalArgumentException("unknown function code: " + code);
        }
    }

    public boolean isError() {
        return this.code - ModbusConstants.ERROR_OFFSET >= 0;
    }
}
